package com.adwin.addcoin.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.itxca.msa.IMsa
import com.itxca.msa.msa

abstract class BaseFragment<VB : ViewBinding, VM : ViewModel>(
    private val inflater: (LayoutInflater, ViewGroup?, Boolean) -> VB,
    private val viewModelClass: Class<VM>?,
    private var isUsePublicViewModel: Boolean = false
) : Fragment(), IMsa by msa() {


    val myViewModel by lazy {
        val viewModelProvider = ViewModelProvider(this)
        viewModelClass?.let {
                viewModelProvider[it]
        }
    }

    val publicViewModel by lazy {
        if (isUsePublicViewModel) {
            //使用requireActivity保证publicViewModel与activity的生命周期一致，在此activity内的fragment共享
            ViewModelProvider(requireActivity())[PublicViewModel::class.java]
        } else {
            null
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = inflater(inflater, container, false)
        initFragment(binding, savedInstanceState)
        return binding.root
    }

    abstract fun onBackPressed():Boolean

    abstract fun initFragment(
        binding: VB,
        savedInstanceState: Bundle?
    )

}